package btc

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/coin-kit/btc-tx"
	"gitee.com/coin-kit/btc-tx/address"
	"github.com/astaxie/beego"
)

type Json1 struct {
	Tx_hash string `json:"tx_hash"`
	Script string `json:"script"`
	Value int64 `json:"value"`
	Tx_index int64 `json:"tx_index"`

}

type JsonUnspent struct {
	Unspent_outputs []Json1 `json:"unspent_outputs"`
}

func GetCoinByAddress(Unspent string) ([]*btctx.Coin,error) {
	var coin []*btctx.Coin
	var UnspentData JsonUnspent

	err := json.Unmarshal([]byte(Unspent), &UnspentData)
	if err != nil  {
		return  coin, err
	}
	if len(UnspentData.Unspent_outputs) <= 0 {
		return coin,errors.New("余额不足！")
	}

	for _,v:=  range UnspentData.Unspent_outputs {
		fmt.Println(v)
		var coin0 btctx.Coin
		coin0.Amount = uint64(v.Value)
		coin0.PkScript = v.Script
		coin0.TxHash = v.Tx_hash
		coin0.Index = uint32(v.Tx_index)
		coin = append(coin, &coin0)
	}
	return coin,nil
}
func GetUnSign(Unspent,From,To string,Amount,Fee int64) (string,error){

	var btc = btctx.NewBuilder()
	coin,err := GetCoinByAddress(Unspent)

	if err != nil {
		return "",err
	}
	btc.SetCoins(coin)
	btc.SetFee(uint64(Fee))

	if beego.BConfig.RunMode != "dev" {
		btc.SetParams(address.BitcoinMain)
	}else {
		btc.SetParams(address.BitcoinTest)
	}

	btc.AddTxOut(To, uint64(Amount))
	btc.SetRefund(From)
	fmt.Println(coin)
	return  btc.Build()

}